package com.aoip.telemetry.telemetry.datastorage.service.impl;


import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.datastorage.mapper.ElementDataPersistenceMapper;
import com.aoip.telemetry.telemetry.datastorage.service.ElementSaveService;
import com.aoip.telemetry.telemetry.entity.common.MergeTableDataEntity;
import com.aoip.telemetry.telemetry.entity.common.TableDataEntity;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author chenbai
 * @version 1.0
 * @date 2021/8/2 14:18
 */
@Service
@Slf4j
public class ElementSaveServiceImpl implements ElementSaveService {

    @Value("${aoip.telemetry.analysis.persistence}")
    private boolean persistence;
    @Resource
    private ElementDataPersistenceMapper mapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public Integer saveElementData(List<TableDataEntity> list) {
        int size = 1;
        try {
            // 是否持久化
            if (!persistence) {
                return 1;
            }
            if (list != null && list.size() > 0) {
                mergeColumn(list);
//                size += list.size();
            }
            if (list != null && list.size() > 0) {
                mapper.mysqlSave(list);
//                size += list.size();
            }
        } catch (DuplicateKeyException e) {
            log.info("数据入库失败，主键重复{}，数据集合：{}", e.getMessage(), Arrays.toString(list.toArray()));
        } catch (Exception e) {
            size = -1;
            log.error("数据入库失败，报错为：{}", e.getMessage());
            e.printStackTrace();
        }
        return size;
    }

    private void mergeColumn(List<TableDataEntity> list) {
        Collection<String> keys = redisCache.keys(CacheKeyEnum.MERGE_DATA + ":*");
        List<MergeTableDataEntity> mergeTableDataList = new ArrayList<>();
        keys.forEach(key -> {
            MergeTableDataEntity entity = redisCache.getCacheObject(key);
            mergeTableDataList.add(entity);
        });
        for (MergeTableDataEntity mergeTableEntity : mergeTableDataList) {
            String mergeTableName = mergeTableEntity.getTableName();
            String mergeStCode = mergeTableEntity.getStCode();
            Iterator<TableDataEntity> iterator = list.iterator();
            while (iterator.hasNext()) {
                TableDataEntity entity = iterator.next();
                String tableName = entity.getTableName();
                Map<String, Object> fieldMap = entity.getFieldMap();
                String stCode = entity.getStCode();
                if (mergeTableName.equalsIgnoreCase(tableName) && mergeStCode.equals(stCode)) {
//                    String limitColumn = mergeTableEntity.getLimitColumn();
//                    if (!StringUtils.hasText(limitColumn)) {
//                        // 若合并字段值为空，为防止全表更新，此处必须含有值
//                        continue;
//                    }
                    Map<String, Object> limitMap = new HashMap<>(2);
//                    String[] limitColumns = limitColumn.split(",");
//                    for (String s : limitColumns) {
                    limitMap.put("stcd", mergeStCode);
                    limitMap.put("tm", fieldMap.get("tm"));
//                    }
                    mergeTableEntity.setLimitColumnFieldMap(limitMap);

                    String mergeColumn = mergeTableEntity.getMergeColumn();
                    if (!StringUtils.hasText(mergeColumn)) {
                        // 若合并字段值为空，为防止全表更新，此处必须含有值
                        continue;
                    }
                    String[] mergeColumns = mergeColumn.split(",");
                    Map<String, Object> mergeMap = new HashMap<>();
                    for (String column : mergeColumns) {
                        Object value = fieldMap.get(column);
                        if (value != null) {
                            mergeMap.put(column, value);
                        }
                    }
                    mergeTableEntity.setMergeColumnFieldMap(mergeMap);
                    List<Object> o = mapper.mysqlQuery(mergeTableEntity);
                    if (o == null || o.size() != 1) {
                        // 若此前不存在数据，则新增
                        continue;
                    }
                    mapper.mysqlUpdate(mergeTableEntity);
                    iterator.remove();
                }
            }
        }

    }
}
